﻿<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	class user extends CI_Controller {
		public function __construct()
		{
			parent::__construct();
			//$this->output->enable_profiler(TRUE);
			$this->load->helper('html');
			$this->load->helper('util');
			$this->load->library('form_validation');
			$this->load->config('config_ip');
			$this->load->model('admin/login_model', 'login_model');
			session_start(); 
			/*if (!in_array($this->get_IP_address(), $this->config->item('admin_ips')))
			{
			   show_404();
			}*/
		}

		public function index()
		{
			if(isset($_SESSION['userinfo']))
			{       
				redirect('/cms/news', 'refresh');				
			}
			$this->load->view('admin/login_view');
		}
		
		private	function get_IP_address()
		{
			foreach (array('HTTP_CLIENT_IP',
				'HTTP_X_FORWARDED_FOR',
				'HTTP_X_FORWARDED',
				'HTTP_X_CLUSTER_CLIENT_IP',
				'HTTP_FORWARDED_FOR',
				'HTTP_FORWARDED',
				'REMOTE_ADDR') as $key){
					if (array_key_exists($key, $_SERVER) === true){
						foreach (explode(',', $_SERVER[$key]) as $IPaddress){
							$IPaddress = trim($IPaddress); // Just to be safe
							
							if (filter_var($IPaddress,
									FILTER_VALIDATE_IP,
									FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
								!== false) {
								
								return $IPaddress;
							}
						}
					}
				}
			}
			
		public function login()
		{
			$data = array();	
				
			if($this->input->post())
			{
				$result['errorCode']=1;
				$this->form_validation->set_rules('name', 'Username', 'trim|required');
				$this->form_validation->set_rules('pass', 'Password', 'required');
				if($this->form_validation->run() == TRUE)
				{
					// Login
					$result = $this->login_model->login($this->input->post('name'),$this->input->post('pass'));
					if($result['errorCode']==200)
					{
						$_SESSION['userinfo']=$result['data'];
						redirect('/cms/news', 'refresh');
					}
					else
					{
							$data['error'] =convert_errorcode($result['errorCode']);
					}
				}
				else
				{
				//	$data['error'] = validation_errors();
				}
			}
				
			$this->load->view('admin/login_view',$data);
		}
		
		public function logout()
		{
			unset($_SESSION['userinfo']);
			session_destroy();
			redirect('/cms/', 'refresh');
		}
	
	}
